package com.hong.springboot.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hong.springboot.api.IUserService;
import com.hong.springboot.config.Constants;
import com.hong.springboot.entity.User;
import com.hong.springboot.utils.DataResponse;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @author: csh
 * @Date: 2021/3/16 11:14
 * @Description:用户监听
 */
@Service
@Log4j2
public class UserListener {

    @Reference
    private IUserService userService;

    @Autowired
    private ObjectMapper objectMapper;



    @RabbitHandler
    @RabbitListener(queues = Constants.MQ_BASE_USER_MESSAGE_QUEUE,containerFactory ="rabbitListenerContainerFactory")
    public void onMessage(Message msg) {
        log.info("需要添加的值{}",JSONObject.toJSONString(msg));
        if(null==msg || msg.getBody()==null){
            return;
        }
        try {
            String messageBody = new String(msg.getBody());
            User user = objectMapper.readValue(messageBody.getBytes("UTF-8"),User.class);
            DataResponse<Boolean> save = userService.reallySave(user);
            if(save==null || !save.getData()){
                log.info("添加失败，原因{}",JSONObject.toJSONString(save));
            }
        }catch (Exception e){
            log.error("添加出错",e);
        }


    }

}
